import { message } from "ant-design-vue";
import { reactive } from "vue";

/* eslint-disable */

interface UploadFile {
  size: number;
  url: string;
  id: string;
  absolutePath: string;
}


export const getFileName = (val: string): string => {
  const raw = val;

  const matcher = raw.match(/filename[.*?]*=([\s\S]+)$/);
  // 不去捕获错误，目的没有达到
  return decodeURIComponent(matcher[1]);
};


interface Downloader {
  (file: File): void;
  fromId(id: string): void;
  fromBlob(blob: Blob, fileName: string): void;
  /**
   * 
   * @param url 阿里 oss 返回的url
   */
  fromUrl(url: string, fileName?: "parser" | string): void;
  fromString(content: string, miniType?: string): void;
  fromStream(stream: Promise<ServiceStructure>): void;
}


export function useFileService() {

  const existFileList = reactive([]);
  let prevFile: File = null;

  const filerReader = new FileReader();
  const a = document.createElement("a");

  const download: Downloader = (file: File) => {

    let fileName = file.name;

    filerReader.onload = () => {
      let blob = new Blob([filerReader.result], { type: file.type });
      download.fromBlob(blob, fileName);
    };

    filerReader.readAsArrayBuffer(file);
  };

  download.fromBlob = (blob: Blob, fileName: string) => {
    return new Promise<boolean>((resolve) => {
      let url = URL.createObjectURL(blob);

      a.download = fileName;
      a.href = url;
      a.click();

      let id = setTimeout(() => {
        clearTimeout(id);
        URL.revokeObjectURL(url);
        resolve(true);
      });
    });
  };
  download.fromId = async (_id: string) => {
    // 等待后台文件下载的id接口
    try {
      // await download.fromStream(fileUploadService.download({ fileId: _id }))
    } catch (exx) {
      console.log(exx);
      message.error("文件下载失败");
    }
  };

  download.fromUrl = (url: string, fileName = "parser") => {
    let name = fileName;

    if (fileName === "parser") {
      // name = 
      try {
        name = /([\d\W\w]+)\.[\w]+$/g.exec(name)[1];
      } catch (exx) {
        throw exx;
      }
    }

    fetch(url)
      .then(stream => stream.blob())
      .then(rs => {
        download.fromBlob(rs, name);
      });
  };
  download.fromString = (content: string, fileName: string, miniType?: string) => {
    let type = miniType ?? "plgin/text";
    let blob = new Blob([content], { type });
    download.fromBlob(blob, fileName);
  };
  download.fromStream = async (stream: Promise<ServiceStructure<Blob>>) => {
    let res = await stream;

    let fileName = getFileName(res.fetch.headers.get("content-disposition"));
    let blob = res.data;
    return download.fromBlob(blob, fileName);
  };

  return {
    watch() {

    },
    use(file: File) {
      prevFile = file;
    },
    size(max: number, cb: () => void, file?: File) {
      let argFile = file;

      if (!(argFile instanceof File)) {
        argFile = prevFile;
      }
      if (!(argFile instanceof File)) {
        throw (Error("file arg is not a File"));
      }

      if (argFile.size > max) {
        cb();
        throw Error("size");
      }
    },
    suffix(accept: string, cb: () => void, file?: File) {
      let argFile = file;

      if (!(argFile instanceof File)) {
        argFile = prevFile;
      }
      if (!(argFile instanceof File)) {
        throw (Error("file arg is not a File"));
      }

      if (!accept.includes(argFile.name.split(".").pop())) {
        cb();
        throw Error("accept");
      }
    },
    download,
    upload(file?: File): Promise<UploadFile> {
      return new Promise<UploadFile>((resolve, reject) => {
        let argFile = file;

        if (!(argFile instanceof File)) {
          argFile = prevFile;
        }
        if (!(argFile instanceof File)) {
          reject(Error("file arg is not a File"));
          return;
        }

        const fd = new FormData();
        fd.append("file", argFile);

        fileUploadService.upload.request<ServiceStructure>({
          body: fd
        })
          .then(rs => {
            if (rs.ok) {
              existFileList.push(rs.data);
              resolve(rs.data);
            }
            throw new Error(rs.message);
          })
          .catch(reject);
      });
    },
    delete(url: string) {
      return new Promise<boolean>((resolve, reject) => {

        fileUploadService.delete<ServiceStructure>({
          filePath: url
        })
          .then(rs => {
            if (rs.code === 0 && rs.ok) {
              // existFileList.push(rs.data);
              resolve(true);
              return;
            }
            throw new Error(rs.message);
          })
          .catch((exx) => {
            console.log(exx);
            resolve(false);
          });
      });
    },
    getFileList() {
      return existFileList;
    }
  }
}


/*
 
if (typeof ratio !== "undefined" && !(/(jpg|png|image)/.test(fileType.toString()))) {
  const validateRatio = function validateFileSize(file: FileType): Promise<ValidateType | null> {
    if (localFileReader === null) {
      localFileReader = new FileReader();
    }
    if (localImageNode === null) {
      localImageNode = document.createElement("img");
    }

    return new Promise((resolve, reject) => {
      localFileReader.onload = function () {
        localImageNode.onload = function () {
          const imageWidth = localImageNode.width, imageHeight = localImageNode.height;

          if (ratio.height < imageHeight || ratio.width < imageWidth) {
            reject({ uid: file.uid, fileValidateErrorMessage: `图片分辨率大于 ${ratio.height} * ${ratio.width}`, fileName: file.name });
            return;
          }
          resolve(null);
          localImageNode = localFileReader.onload = null;
        };
        localImageNode.src = localFileReader.result as string;
      };

      localFileReader.readAsDataURL(file);
    });
  };

 
*/
